<template>
  <Teleport to="body">
    <div>
      <input ref="inputRef" v-model="val" style="display: block" class="nvr-input" :style="style" />
    </div>
  </Teleport>
</template>

<script setup lang="ts">
import { ref, watchEffect, onMounted, Ref } from 'vue'
import * as PIXI from 'pixi.js'
import hblCursor from './cursor'
import hbltable from './table'
import hblText from './text'
import { createEf } from '@/utils/ef'

const props = defineProps({
  fontSize: { type: Number, default: 24 }, // 字体大小
  showSize: { type: Number, default: 5 }, // 最多可以展示的字符数
  // number: { type: Boolean, default: false }, // 是否是数字
})
const inputRef = ref<HTMLInputElement | null>(null)
const val = ref('')
const style = ref<{
  left: string | number
  top: string | number
}>({
  left: 0,
  top: 0,
})
const textContainer = hblText(val, props.fontSize) // 文字
// 创建文字容器
const container = new PIXI.Container()
onMounted(async () => {
  const table = hbltable(props.fontSize, props.showSize) // 表格底部
  const { cursor, focused } = await hblCursor(inputRef as Ref<HTMLInputElement>, props.fontSize) // 光标
  container.addChild(table)
  container.addChild(textContainer)
  container.addChild(cursor)
  container.position.set(100, 100)
  createEf(
    () => {
      focused.value = true
    },
    { type: 'click', peimi: true },
  ).whiteAdd(container)

  // 输入框的值变化时, 更新文本内容
  watchEffect(() => {
    // console.log(val.value)
    cursor.position.set(textContainer.width, 0)
    style.value = {
      left: container.x + 'px',
      top: container.y + 'px',
    }
  })
})
defineExpose({
  container,
})
</script>

<style scoped lang="scss">
.nvr-input {
  width: 1 px;
  border: none;
  position: fixed;
  color: transparent;
  left: 0;
  top: 0;
  &:focus {
    outline: none;
    caret-color: transparent;
  }
  z-index: -999;
}
</style>
